﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace YellowMap.Ultility
{
    class Logger
    {
        const string LogFileName = "TMSLogFile.txt";
        public static string emailTo = "pkhuy@tma.com.vn";
        public static string emailCc = "huy.phungkhac@gmail.com";
        public static string emailSubject = "Visual Map - Log";

        /*
         * [pkhuy] write to log file
         */
        public static async Task WriteLog(string text)
        {
            string oldLog = await ReadFile();
            text = oldLog + "~" + DateTime.Now + "~" + text;
            text = text.Replace("~", System.Environment.NewLine);
            
            byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(text);
                        
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file = await local.CreateFileAsync(LogFileName, CreationCollisionOption.OpenIfExists);
            
            using (var s = await file.OpenStreamForWriteAsync())
            {
                s.Write(fileBytes, 0, fileBytes.Length);
            }
        }

        /*
         * [pkhuy] read content in log file
         */
        public static async Task<String> ReadFile()
        {
            string strLog = "";
            
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

            if (local != null)
            {
                // Get the file.
                var file = await local.CreateFileAsync(LogFileName, CreationCollisionOption.OpenIfExists);
                var f = await local.OpenStreamForReadAsync(LogFileName);

                // Read the data.
                using (StreamReader streamReader = new StreamReader(f))
                {
                    strLog = streamReader.ReadToEnd();
                }

            }

            return strLog;
        }
    }
}
